import React, { Component, createRef, PureComponent } from 'react'

class Counter extends PureComponent {
  constructor(props) {
    super(props)

    this.state = {
      counter: 0
    }
  }

  render() {
    return (
      <div>
        <h2>当前计数: {this.state.counter}</h2>
        <button onClick={() => { this.increment() }}>+1</button>
      </div>
    )
  }

  increment() {
    this.setState({
      counter: this.state.counter + 1
    })
  }

}


export default class App extends Component {
  constructor(props) {
    super(props)

    this.titleRef = createRef()
    this.counterRef = createRef()
    this.titleEl = null

  }

  render() {
    return (
      <div>
        {/* 使用方式一：字符串 */}
        <h2 ref="titleRef">Hello React</h2>
        {/* 使用方式二：React推荐的方式 */}
        <h2 ref={this.titleRef}>呵呵</h2>
        {/* 使用方式三：函数方式 */}
        <h2 ref={(arg) => { this.titleEl = arg }}>函数</h2>
        <button onClick={() => { this.changeText() }}>改变文本</button>
        <hr />
        <Counter ref={this.counterRef}/>
        <button onClick={() => { this.appBtnClick() }}>APP按钮</button>
      </div>
    )
  }

  changeText() {
    // 方式一
    this.refs.titleRef.innerHTML = "你好"
    // 方式二
    this.titleRef.current.innerHTML = "你好"
    // 方式三
    this.titleEl.innerHTML = "你好"
  }

  appBtnClick() {
    // 不能在函数组件上使用ref属性
    console.log(this.counterRef.current.increment())
  }

}
